/**
 * @Title:  VolleyBasic.java 
 * @Copyright:  XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
 * @Description:  TODO<请描述此文件是做什么的> 
 * @author:  MeiYi 
 * @data:  2016-4-6 下午1:46:21 
 * @version:  V1.0 
 */

package artid.com.arttogoa.volley;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import artid.com.arttogoa.LoginAvtivity;
import artid.com.arttogoa.MainActivity;
import artid.com.arttogoa.R;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.AppItem;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.ToastUtil;
import com.android.volley.Request;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.umeng.socialize.utils.Log;

/**
 * TODO<请描述这个类是干什么的>
 * 
 * @author 熊彬
 * @data: 2016-4-6 下午1:46:21
 * @version: V1.0
 */
public class VolleyBasic {

	private static VolleyBasic vb;
	private static Activity activity;
	public static Dialog progressDialog;

	private VolleyBasic() {

	}

	/**
	 * 获取类实例对象
	 * 
	 * @return MyActivityManager
	 */
	public static VolleyBasic getInstance(Activity activity) {
		// if (null == vb) {
		vb = new VolleyBasic();
		// }
		vb.activity = activity;
		return vb;
	}

	private String url;
	private Map<String, String> parameter;
	private VolleyCallback callBcak;
	private Class<? extends AppItem> cls;

	/**
	 * 
	 */
	public void post(String url, Map<String, String> parameter,
			Class<? extends AppItem> cls, VolleyCallback callBcak) {
		// TODO Auto-generated method stub
		this.url = url;
		this.parameter = parameter;
		this.callBcak = callBcak;
		this.cls = cls;
		System.out.print("Posturl:" + url + " ");
		printHashMap("请求参数：", parameter);
		start(Request.Method.POST);
	}

	@SuppressLint("InflateParams")
	@SuppressWarnings("deprecation")
	public void start(int Method) {
		if (activity == null) {
			return;
		}
		showLoding(activity);
		VolleyRequest stringRequest = new VolleyRequest(Method, url,
				new Listener<String>() {
					

					@Override
					public void onResponse(String returnString) {
						disMissLoding();
						System.out.println("onResponse=" + returnString);
						VolleyData VD = new VolleyData(returnString, cls);
						if (VD.getCode() == -99) {
							disMissLoding();
							System.out.println("VD.getCode()=" + VD.getCode());
							showRemoteLoginDialog(activity);
							return;
						}
						if (!TextUtils.isEmpty(VD.getJson())) {
							System.out.println(VD.getJson());
						}
						if (VD.getCode() != VolleyData.Success) {
							ToastUtil.toast(activity, VD.getMsg());
							disMissLoding();
							return;
						}
						callBcak.onSuccess(VD);
					}
				}, new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError volleyError) {
						disMissLoding();
						System.out.print("volleyError"
								+ volleyError.getMessage());
						ToastUtil.toast(activity, "网络请求失败");
						callBcak.onError(volleyError);
					}
				}) {
			@Override
			protected Map<String, String> getParams() {
				// 在这里设置需要post的参数
				Map<String, String> map = new HashMap<String, String>();
				return parameter != null ? parameter : map;
			}

		};
		VolleySingleton volleySingleton = new VolleySingleton(activity);
		VolleySingleton.getVolleySingleton(activity.getApplicationContext())
				.addToRequestQueue(stringRequest);
	}

	/**
	 * 主要用于特殊请求（isShowLodingDialog:true开启加载 false不开启
	 * ,isCloseLodingDialog:true关闭加载 fals不关闭）
	 */
	public void post(Boolean isShowLodingDialog, Boolean isCloseLodingDialog,
			String url, Map<String, String> parameter,
			Class<? extends AppItem> cls, VolleyCallback callBcak) {
		// TODO Auto-generated method stub
		this.url = url;
		this.parameter = parameter;
		this.callBcak = callBcak;
		this.cls = cls;
		System.out.print("Posturl:" + url + " ");
		printHashMap("请求参数：", parameter);
		start(Request.Method.POST, isShowLodingDialog, isCloseLodingDialog);
	}

	private String artBo;

	@SuppressLint("InflateParams")
	public void start(int Method, final Boolean isShowLodingDialog,
			final Boolean isCloseLodingDialog) {
		artBo = MySharedPreferences.getMySharedPreferences(activity).getValue(
				Cache.ARTREC_STATUS, "no");
		if (isShowLodingDialog == true) {
			showLoding(activity);
		}
		VolleyRequest stringRequest = new VolleyRequest(Method, url,
				new Listener<String>() {

					@Override
					public void onResponse(String returnString) {
						if (isCloseLodingDialog == true) {
							Log.d("log", "onResponse的disMissLoding（）执行了");
							disMissLoding();
						}
						VolleyData VD = new VolleyData(returnString, cls);
						/*
						 * if (!artBo.equals("yes")) { callBcak.onSuccess(VD);
						 * return; }
						 */
						if (VD.getCode() == -99) {
							disMissLoding();
							showRemoteLoginDialog(activity);
							return;
						}
						if (!TextUtils.isEmpty(VD.getJson())) {
							System.out.println(VD.getJson());
						}
						if (VD.getCode() != VolleyData.Success) {
							disMissLoding();
							ToastUtil.toast(activity, VD.getMsg());
							return;
						}
						callBcak.onSuccess(VD);
					}
				}, new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError volleyError) {
						if (isCloseLodingDialog == true) {
							Log.d("log", "onResponse的onErrorResponse（）执行了");
							disMissLoding();
						}
						System.out.println("artBo=" + artBo);
						if (!artBo.equals("yes")) {
							disMissLoding();
							ToastUtil.toast(activity, "服务器开小差了~");
						}
						System.out.print("volleyError"
								+ volleyError.getMessage());
						callBcak.onError(volleyError);
					}
				}) {
			@Override
			protected Map<String, String> getParams() {
				// 在这里设置需要post的参数
				Map<String, String> map = new HashMap<String, String>();
				return parameter != null ? parameter : map;
			}
		};
		VolleySingleton volleySingleton = new VolleySingleton(activity);

		VolleySingleton.getVolleySingleton(activity.getApplicationContext())
				.addToRequestQueue(stringRequest);
	}

	public static void printHashMap(String tag, Map<String, String> hashMap) {
		Set<String> keys = hashMap.keySet();
		for (String key : keys) {
			System.out.print(tag + "===" + key + "--" + hashMap.get(key));
		}
	}

	static ImageView fireImg;
	static AnimationDrawable AniDraw;

	public static void showLoding(Context activity) {
		if (ArtWorkApp.isForeground(activity,
				StringUtils.substringBeforeLast(activity.toString(), "@")) != true) {
			return;
		}
		if (progressDialog == null) {
			LayoutInflater inflater = LayoutInflater.from(activity);
			View v = inflater.inflate(R.layout.loading, null);// 得到加载view
			RelativeLayout layout = (RelativeLayout) v
					.findViewById(R.id.rel_dialog);// 加载布局
			fireImg = (ImageView) v.findViewById(R.id.iv);
			AniDraw = (AnimationDrawable) fireImg.getBackground();
			AniDraw.start();
			progressDialog = new Dialog(activity, R.style.dialog);// 创建自定义样式dialog
			progressDialog.setCancelable(false);// 不可以用“返回键”取消
			progressDialog.setContentView(layout,
					new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.FILL_PARENT,
							LinearLayout.LayoutParams.FILL_PARENT));// 设置布局
		}
		if (activity != null && !progressDialog.isShowing()) {
			progressDialog.show();
		}
	}

	public static void disMissLoding() {
		if (AniDraw != null && AniDraw.isRunning()) {
			AniDraw.stop();
			AniDraw = null;
		}
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	public static ImageListener getImageListener(final ImageView view,
			final int defaultImageResId, final int errorImageResId,
			final String url) {
		return new ImageListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				if (errorImageResId != 0) {
					view.setImageResource(errorImageResId);
				}
			}

			@Override
			public void onResponse(ImageContainer response, boolean isImmediate) {
				if (response.getBitmap() != null) {
					// 在这里可以设置，如果想得到圆角图片的画，可以对bitmap进行加工，可以给imageview加一个
					// 额外的参数
					String urlTag = (String) view.getTag();
					if (urlTag != null && urlTag.trim().equals(url)) {
						view.setImageBitmap(response.getBitmap());
					}
				} else if (defaultImageResId != 0) {
					view.setImageResource(defaultImageResId);
				}
			}
		};
	}

	/**
	 * 异地登陆提示框
	 * 
	 * @param list
	 */
	public static void showRemoteLoginDialog(final Activity mActivity) {
		disMissLoding();
		if (AlertUtils.alertDialog == null
				|| !AlertUtils.alertDialog.isShowing()) {
			AlertUtils.MessageAlertDialog(
					mActivity,
					"您的账号已经在其他设备登陆，是否需要重新登陆？",
					Integer.parseInt(NetUtils.getDisplayMetrics(
							(Activity) mActivity).get(NetUtils.DM_WIDTH)),
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							switch (v.getId()) {
							case R.id.tv_ok:
								// 确定
								IntentFilter filter = new IntentFilter(
										"com.VolleyBasic.receiver");
								mActivity.registerReceiver(broadcastReceiver,
										filter);
								// 注册当前广播
								AlertUtils.dismiss();
								Intent intent = new Intent(mActivity,
										LoginAvtivity.class);
								intent.putExtra("isRemoteLogin", true);
								mActivity.startActivity(intent);
								MainActivity.isRefreshPersonal = true;
								new Handler().postDelayed(new Runnable() {

									@Override
									public void run() {
										// 发送给登陆页面告诉异地登陆
										Intent intent2 = new Intent(
												"com.LoginAvtivity.receiver");
										intent2.putExtra("isRemoteLogin", true);
										mActivity.sendBroadcast(intent2);
									}
								}, 1500);
								break;
							case R.id.tv_no:
								mActivity.finish();
								break;
							default:
								break;
							}
						}
					});
		}
	}

	// 广播监听
	static BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getBooleanExtra("isRemoteLogin", false)) {
				// 判断是否为异地登陆
				Log.d("log", "VolleyBasic接收：异地登陆成功");
				// 关闭广播
				context.unregisterReceiver(broadcastReceiver);
			}
		}
	};

}
